<template>
    <Modal
        title="售后维修"
        width="640"
        :value="show"
        :mask-closable="false"
        @on-visible-change="setVisibility">

        <Alert v-show="isUrgencyTime">需3小时内处理的维修工单，请拨打4000-101-110，联系客服</Alert>

        <Form
            style="padding:0 30px;"
            :model="form"
            :rules="rules"
            ref="createService"
            :label-width="125"
            :show-message="false"
            label-position='right'>

            <Row :gutter="30" class="margin-top-20">
                <i-col span="12">
                    <FormItem label="联系人"  prop="subscribe.name" >
                        <i-input v-model="form.subscribe.name"></i-input>
                    </FormItem>
                </i-col>
                <i-col span="12">
                    <FormItem label="联系人电话" prop="subscribe.phone">
                        <Input v-model="form.subscribe.phone"></Input>
                    </FormItem>
                </i-col>
            </Row>

            <!-- noop function 防止初始化编辑时,触发on-change -->
            <FormItem label="公寓地址" prop="home_id">
                <Select
                    v-if="show && !fixedHome"
                    filterable
                    remote
                    :remote-method="searchHomes"
                    placeholder="请输入公寓地址"
                    @on-change="getRoom"
                    :loading="loadingHomes">
                    <Option
                        v-for="(option, index) in homes"
                        :key="index"
                        :value="option.id">
                        {{concatLocation(option) + '(' + option.home_name + ')'}}
                    </Option>
                </Select>
                <!-- 固定地址时候 homes只有一个数组 -->
                <i-input
                    v-else
                    :disabled="fixedHome"
                    :value="homes.length ? concatLocation(homes[0]) : ''"
                ></i-input>
            </FormItem>

            <!-- <FormItem label="期待上门时间：" prop="subscribe.expected_time">
                <Row type="flex" :gutter="10">
                    <Col span="12">
                        <DatePicker
                            style="width: 100%"
                            v-model="form.subscribe.expected_time"
                            type="datetime"
                            format="yyyy-MM-dd HH:ss"
                            placeholder="请选择时间"
                            @on-change="checkExpectedTime"
                            :options="options"></DatePicker>
                    </Col>
                    <Col span="12">
                        <Select v-model="form.subscribe.expected_period">
                            <Option :value="2" :disabled="isNotMoring">上午</Option>
                            <Option :value="3">下午</Option>
                        </Select>
                    </Col>
                </Row>
            </FormItem>
            <FormItem label="时段" style="display:none" prop="subscribe.expected_period"></FormItem> -->

            <div class="cs-item" v-for="(item, index) in form.faults" :key="index">
                <FormItem
                    label="房间号"
                    :prop="'faults.' + index + '.room_id'"
                    :rules="{required: true}">
                    <Row :gutter="10" type="flex">
                        <i-col span="20">
                            <Select
                                v-model="item.room_id"
                                @on-change="form.faults[index].device_id = ''">
                                <Option
                                    v-for="room in rooms"
                                    :value="room.id"
                                    :key="room.id">{{room.room_name}}</Option>
                            </Select>
                        </i-col>
                        <i-col span="4">
                            <i-button @click="handleNewDelete(index)">删除</i-button>
                        </i-col>
                    </Row>
                </FormItem>
                <FormItem
                    label="故障设备"
                    :prop="'faults.' + index + '.device_id'"
                    :rules="{required: true}">
                    <Select
                        v-model="item.device_id"
                        placeholder="请选择故障设备">
                        <Option
                            v-for="device in devices[form.faults[index].room_id]"
                            :value="device.id"
                            :key="device.id"
                            :disabled="selectedDevices.includes(device.id)">
                            {{device.description}} [{{device.device_type | deviceType}}]
                        </Option>
                    </Select>
                </FormItem>
                <FormItem
                    label="故障说明"
                    :rules="{required: true}"
                    :prop="'faults.' + index + '.description'">
                    <Input v-model="item.description"></Input>
                </FormItem>
                <FormItem
                    label="故障时间"
                    :rules="{required: true}"
                    :prop="'faults.' + index + '.fault_time'">
                    <DatePicker
                        style="width: 100%"
                        v-model="item.fault_time"
                        type="datetime"
                        format="yyyy-MM-dd HH:ss"
                        placeholder="请选择时间"
                        :options="options"></DatePicker>
                </FormItem>
            </div>
            <p class="text-right">
                <i-button type="primary" @click="handleAdd">添加新设备</i-button>
            </p>
        </Form>

        <div slot="footer">
            <Button type="text" @click="setVisibility(false)">取消</Button>
            <Button type="primary" :loading="loading" @click="handleSubmit">保存</Button>
        </div>
    </Modal>
</template>

<script>
import dayjs from 'dayjs'
import validate from '@/libs/validate.js'
import { http, api } from '@/libs/http'
import util from '@/libs/util'

/**
 * home_id相关使用 string 是因为iview 2.14.2的bug
 */
export default {
  name: 'create-service',
  props: {
    show: Boolean,
    ticket: Object,
    data: Object,
    fixedHome: Boolean
  },
  computed: {
    // isNotMoring () {
    //     const { todayNoon, midnight } = this
    //     const now = +new Date()
    //     const time = this.form.subscribe.expected_time || new Date()
    //     const appointmentTime = dayjs(time).valueOf()
    //     if (now > todayNoon && midnight >= appointmentTime) {
    //         if (this.form.subscribe.expected_period === 2) {
    //             this.form.subscribe.expected_period = 3
    //         }
    //         return true
    //     }
    //     return false
    // },
    isUrgencyTime () {
      // 当前选择的时间戳
      const current = dayjs().valueOf()
      // 当前时间在今天0-9点和20-24点时间, 提出提示
      return (current > this.maxLimit && current < this.midnight) || current < this.minLimit
    },
    selectedDevices () {
      return this.form.faults.map(item => item.device_id)
    }
  },
  data () {
    return {
      loading: false,
      maxLimit: dayjs()
        .hour(20)
        .minute(0)
        .second(0)
        .valueOf(), // 今天20点之后
      minLimit: dayjs()
        .hour(9)
        .minute(0)
        .second(0)
        .valueOf(), // 明天9点前
      todayNoon: dayjs()
        .hour(12)
        .minute(0)
        .second(0)
        .valueOf(),
      midnight: dayjs()
        .hour(23)
        .minute(59)
        .second(59)
        .valueOf(),
      options: {
        disabledDate (date) {
          return date && date.valueOf() > Date.now()
        }
      },
      loadingHomes: false,
      homes: [],
      rooms: [],
      devices: {},
      faultsModel: {
        room_id: '',
        device_id: '',
        description: '',
        fault_time: ''
      },
      form: {
        home_id: '',
        subscribe: {
          name: '',
          phone: ''
          // expected_time: '',
          // expected_period: ''
        },
        faults: [
          {
            room_id: '',
            device_id: '',
            description: '',
            fault_time: ''
          }
        ] // 房间信息
      },
      rules: {
        home_id: { required: true },
        'subscribe.name': { required: true },
        'subscribe.phone': { required: true, validator: validate.validPhone }
        // 'subscribe.expected_time': { required: true },
        // 'subscribe.expected_period': { required: true }
      },
      deviceType: [
        { id: 1, name: '网关' },
        { id: 2, name: '门锁' },
        { id: 3, name: '电表' },
        { id: 4, name: '采集器' },
        { id: 5, name: '水表网关' },
        { id: 6, name: '冷水表' },
        { id: 7, name: '热水表' }
      ]
    }
  },
  watch: {
    show (n) {
      if (!n) {
        this.$refs.createService.resetFields()
        this.rooms = []
        this.homes = []
        this.devices = {}
        this.form.faults = [{ ...this.faultsModel }]
      } else {
        const { userName, telephone } = this.$store.state.user
        this.form.subscribe.name = userName
        this.form.subscribe.phone = telephone
        if (this.data) {
          this.initData()
        }
      }
    }
  },
  methods: {
    concatLocation: util.concatLocation,
    async initData () {
      this.homes.push(this.data.home)
      this.form.home_id = this.data.home.id
      await this.getRoom(this.data.home.id)
      this.form.faults[0].room_id = this.data.room_id
    },
    setVisibility (val) {
      this.$emit('update:show', val)
    },
    // checkExpectedTime () {
    //     if (this.dateToValue(this.form.subscribe.expected_time) < dayjs().valueOf()) {
    //         this.$Message.error('期待上门时间要大于当前时间')
    //         return true
    //     }
    //     return false
    // },
    dateToValue (date) {
      if (date instanceof dayjs) return date.valueOf()
      return dayjs(date).valueOf()
    },
    haveDevice (room, type) {
      const devices = room.devices.map(device => device.device_type)
      if (devices.includes(type)) {
        return ' [已有该设备]'
      }
      return ''
    },
    handleAdd () {
      this.form.faults.push({ ...this.faultsModel })
    },
    handleNewDelete (index) {
      if (this.form.faults && this.form.faults.length === 1) {
        this.$Message.error('至少填写一个故障设备')
        return
      }
      this.form.faults.splice(index, 1)
    },
    searchHomes (query) {
      if (this.fixedHome) return
      return new Promise(resolve => {
        this.form.faults = [{ ...this.faultsModel }]
        // 搜索房源
        if (query) {
          let params = { keyword: query }
          this.loadingHomes = true
          http.request(this, api.home_list, null, params, res => {
            resolve()
            if (res) {
              this.homes = res.homes
            }
            this.loadingHomes = false
          })
        } else {
          this.homes = []
          resolve()
        }
      })
    },
    getRoom (id) {
      return new Promise(resolve => {
        if (!id) {
          resolve()
          return
        }
        this.form.home_id = id
        http.request(this, api.room_list, [id], { with_device: 1 }, (res, err) => {
          resolve()
          if (!res || err) return
          this.rooms = res.sort((a, b) => {
            return a.room_name - b.room_name || b.room_type - a.room_type || a.room_name.localeCompare(b.room_name)
          })
          const devicesList = {}
          res.forEach(room => {
            devicesList[room.id] = room.devices
          })
          this.devices = devicesList
        })
      })
    },
    handleSubmit () {
      if (this.loading) return
      this.loading = true
      this.$refs.createService.validate(valid => {
        if (valid) {
          this.create()
        } else {
          this.$Message.error('信息填写错误')
          this.loading = false
        }
      })
    },
    generateRequestData () {
      const { subscribe } = this.form
      const data = {
        ...this.form,
        service_target: -1, // 前台接口不加错误
        subscribe: { ...subscribe }
      }
      data.faults = JSON.parse(JSON.stringify(data.faults))
      data.faults.forEach(item => {
        item.fault_time = dayjs(item.fault_time).valueOf()
      })
      // data.subscribe.expected_time = dayjs(data.subscribe.expected_time).valueOf()
      return data
    },
    /**
         * 创建新工单
         * form.faults绑定的是room id,
         * 请求的faults转换成房间信息数组
         */
    create () {
      // if (this.checkExpectedTime()) return
      const data = this.generateRequestData()
      http.request(this, api.ticket_add, [2], data, (res, err) => {
        this.loading = false
        if (err) {
          this.$Message.warning('添加失败: ' + err.data.err_msg)
          return
        }
        this.$Message.success('添加成功')
        this.$emit('refresh')
        this.setVisibility(false)
      })
    }
  }
}
</script>

<style>
.cs-item {
    position: relative;
    padding-top: 20px;
    border-top: 1px solid #eee;
}
</style>